package com.usian.app.gateway.filter;

import com.usian.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1：得到请求地址判断  如果是登录 放行
        String url = request.getURI().getPath();
        if(url.contains("/login/login_auth")){
            return chain.filter(exchange);
        }

        //2: 获取请求头token
        String token = request.getHeaders().getFirst("token");

        //3: 判断token是否有效 非空
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4: 有效 token 值 透传到  下游服务中
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int result = AppJwtUtil.verifyToken(claims);
        if(result==-1 ||result==0){
            //有效  拿到token值
            Integer id = (Integer) claims.get("id");
            //透传
            //重新设置token到下游服务  header中
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", id + "");
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
